import jwt from 'jsonwebtoken';
import { config } from '@/config';

/**
 * JWT 负载接口
 */
export interface JwtPayload {
  id: string;
  email: string;
  role?: string;
  iat?: number;
  exp?: number;
}

/**
 * JWT 工具类
 */
export class JwtUtil {
  /**
   * 生成 JWT token
   */
  static generateToken(payload: Omit<JwtPayload, 'iat' | 'exp'>): string {
    return jwt.sign(payload, config.jwt.secret, {
      expiresIn: config.jwt.expiresIn,
    } as jwt.SignOptions);
  }

  /**
   * 验证 JWT token
   */
  static verifyToken(token: string): JwtPayload {
    try {
      return jwt.verify(token, config.jwt.secret) as JwtPayload;
    } catch (error) {
      throw new Error('Invalid token');
    }
  }

  /**
   * 解码 JWT token（不验证签名）
   */
  static decodeToken(token: string): JwtPayload | null {
    try {
      return jwt.decode(token) as JwtPayload;
    } catch {
      return null;
    }
  }

  /**
   * 检查 token 是否过期
   */
  static isTokenExpired(token: string): boolean {
    try {
      const decoded = this.decodeToken(token);
      if (!decoded || !decoded.exp) {
        return true;
      }
      
      const currentTime = Math.floor(Date.now() / 1000);
      return decoded.exp < currentTime;
    } catch {
      return true;
    }
  }

  /**
   * 从请求头中提取 token
   */
  static extractTokenFromHeader(authorization?: string): string | null {
    if (!authorization || !authorization.startsWith('Bearer ')) {
      return null;
    }
    
    return authorization.substring(7);
  }

  /**
   * 刷新 token
   */
  static refreshToken(token: string): string {
    const payload = this.verifyToken(token);
    
    // 移除 iat 和 exp 字段
    const { iat, exp, ...newPayload } = payload;
    
    return this.generateToken(newPayload);
  }
}

export default JwtUtil;